package com.bf.electroplating.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bf.electroplating.mapper.ComProductionMapper;
import com.bf.electroplating.mapper.ComCompanyMapper;
import com.bf.electroplating.pojo.dto.production.ComProductionDTO;
import com.bf.electroplating.pojo.entity.ComProduction;
import com.bf.electroplating.pojo.entity.ComCompany;
import com.bf.electroplating.pojo.entity.ComWorkshop;
import com.bf.electroplating.pojo.entity.PubAttachmentRel;
import com.bf.electroplating.pojo.enums.AttModuleEnums;
import com.bf.electroplating.pojo.vo.production.ComProductionVO;
import com.bf.electroplating.service.ComProductionService;
import com.bf.electroplating.service.PubAttachmentRelService;
import com.bf.electroplating.service.PubAttachmentService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author 15451
* @description 针对表【com_production(电镀生产信息表)】的数据库操作Service实现
* @createDate 2025-05-09 11:11:32
*/
@Service
public class ComProductionServiceImpl extends ServiceImpl<ComProductionMapper, ComProduction>
    implements ComProductionService {

    @Resource
    private ComCompanyMapper companyMapper;
    
    @Resource
    private PubAttachmentService attachmentService;

    @Resource
    private PubAttachmentRelService iPubAttachmentRelService;

    @Override
    public Page<ComProductionVO> getProductionList(ComProductionDTO dto) {
        Page<ComProduction> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<ComProduction> wrapper = new LambdaQueryWrapper<>();

        // 查询条件：电镀镀种
        if (StringUtils.hasText(dto.getElectroplatingType())) {
            wrapper.like(ComProduction::getElectroplatingType, dto.getElectroplatingType());
        }
        if (StringUtils.hasText(dto.getCompanyName())) {
            wrapper.eq(ComProduction::getCompanyId, dto.getCompanyName());
        }

        Page<ComProduction> productionPage = this.page(page, wrapper);
        Page<ComProductionVO> voPage = new Page<>();
        BeanUtils.copyProperties(productionPage, voPage, "records");

        // 获取所有涉及的企业ID
        List<String> companyIds = productionPage.getRecords().stream()
                .map(ComProduction::getCompanyId)
                .filter(StringUtils::hasText)
                .distinct()
                .collect(Collectors.toList());

        // 批量查询企业信息
        Map<String, String> companyNameMap = new HashMap<>();
        if (!companyIds.isEmpty()) {
            LambdaQueryWrapper<ComCompany> companyWrapper = new LambdaQueryWrapper<>();
            companyWrapper.in(ComCompany::getId, companyIds);
            List<ComCompany> companies = companyMapper.selectList(companyWrapper);
            companyNameMap = companies.stream()
                    .collect(Collectors.toMap(ComCompany::getId, ComCompany::getCompanyName, (k1, k2) -> k1));
        }

        // 封装VO对象
        Map<String, String> finalCompanyNameMap = companyNameMap;
        List<ComProductionVO> voList = productionPage.getRecords().stream().map(production -> {
            ComProductionVO vo = new ComProductionVO();
            BeanUtils.copyProperties(production, vo);
            // 设置企业名称
            if (StringUtils.hasText(production.getCompanyId())) {
                vo.setCompanyName(finalCompanyNameMap.getOrDefault(production.getCompanyId(), ""));
            }
            // 设置附件信息
            vo.setAttachmentIds(attachmentService.getWholeFile(production.getId(), AttModuleEnums.PRODUCTION.getCode()));
            return vo;
        }).collect(Collectors.toList());

        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    public ComProductionVO getProductionById(String id) {
        ComProduction production = this.getById(id);
        if (production == null) {
            return null;
        }
        
        ComProductionVO vo = new ComProductionVO();
        BeanUtils.copyProperties(production, vo);
        
        // 查询企业名称
        if (StringUtils.hasText(production.getCompanyId())) {
            ComCompany company = companyMapper.selectById(production.getCompanyId());
            if (company != null) {
                vo.setCompanyName(company.getCompanyName());
            }
        }
        
        // 查询附件信息
        vo.setAttachmentIds(attachmentService.getWholeFile(production.getId(), AttModuleEnums.PRODUCTION.getCode()));
        
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveProduction(ComProductionVO vo) {
        ComProduction production = new ComProduction();
        BeanUtils.copyProperties(vo, production);
        boolean result = this.save(production);
        
        // 保存附件关联
        if (result && vo.getAttachmentIds() != null) {
            attachmentService.saveWholeAttachmentRel(vo.getAttachmentIds(), production.getId(), AttModuleEnums.PRODUCTION.getCode());
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateProduction(ComProductionVO vo) {
        ComProduction production = new ComProduction();
        BeanUtils.copyProperties(vo, production);
        boolean result = this.updateById(production);
        
        // 更新附件关联
        if (result && vo.getAttachmentIds() != null) {
//            attachmentService.deleteByModuleId(production.getId(), AttModuleEnums.PRODUCTION.getCode());
            iPubAttachmentRelService.remove(new LambdaQueryWrapper<PubAttachmentRel>()
                    .eq(PubAttachmentRel::getStorePath, AttModuleEnums.PRODUCTION.getCode())
                    .eq(PubAttachmentRel::getRelationId, production.getId()));
            attachmentService.saveWholeAttachmentRel(vo.getAttachmentIds(), production.getId(), AttModuleEnums.PRODUCTION.getCode());
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteProduction(String id) {
        // 删除附件关联
        attachmentService.deleteByModuleId(id, AttModuleEnums.PRODUCTION.getCode());
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteProduction(List<String> ids) {
        // 批量删除附件关联
        for (String id : ids) {
            attachmentService.deleteByModuleId(id, AttModuleEnums.PRODUCTION.getCode());
        }
        return this.removeByIds(ids);
    }
}




